.PHONY: all build env clean

# project settings
# the main go sources
mains := ./client.go ./server.go ./cmd.go
# build bin directory
bin := bin
# protobuf generate directory
proto := proto
# the protobuf source
protocol := protocol
# the exclude directory
excludes := ./vendor

# get the path
pwd := $(shell pwd)
project-path ?= $(pwd)
package-path ?= $(shell pwd | awk -Fsrc/ '{print $$2}')

# export variable
export GOPATH := $(project-path):$(GOPATH)

# variable
targets := $(patsubst ./%,$(bin)/%,$(patsubst %.go,%,$(mains)))

# version
date := `date '+%Y-%m-%d(%I:%M:%S)'`
build := `git rev-parse HEAD 2>/dev/null`
version := `git describe --abbrev=0 --tags 2>/dev/null`

# get proto files
proto-sources := $(shell find . -path '$(excludes)' -prune -o -type f -name *.proto -print)
proto-pbs := $(notdir $(proto-sources))
proto-pbs := $(proto-pbs:%.proto=$(proto)/%.pb.go)


# compiler ld flags
LDFLAGS-CROSS := -s -w
LDFLAGS-VERSION := -X $(package-path)/version.Version=$(version) -X $(package-path)/version.Date=$(date) -X $(package-path)/version.Build=$(build)


LDFLAGS := $(LDFLAGS-CROSS) $(LDFLAGS-VERSION)


# compiler command
go-build := go build -ldflags "$(LDFLAGS)"



# default all
all: build
	@echo build succeed



# build
build: build-proto $(targets)
	

# build target
$(bin)/%:%.go
	$(go-build) -o $@ $^
	@echo build $@ succeed



# build protobuf
build-proto: $(proto-pbs)
	

# build proto file
$(proto)/%.pb.go:$(protocol)/%.proto
	@mkdir -p $(proto)
	protoc -I $(protocol) -I $(proto) --go_out=plugins=grpc:$(proto) $^
	@echo build $^ succeed


# print env variable
env:
	@echo pwd: $(pwd)
	@echo GOPATH: $(GOPATH)
	@echo project-path: $(project-path)
	@echo package-path: $(package-path)
	@echo targets: $(targets)
	@echo proto-sources: $(proto-sources)
	@echo proto-pbs: $(proto-pbs)
	@echo version: $(version)
	@echo date: $(date)
	@echo build: $(build)


# clean the generates
clean:
	rm -f $(targets) $(proto-pbs)